from django.shortcuts import render
from django.http.response import JsonResponse
from django.views import View
from apps.order.models import OrderInfo
from utils.users import LoginRequiredJSONMixin
from alipay import AliPay
from django.conf import settings
# Create your views here.
class AliPayURLView(LoginRequiredJSONMixin,View):

    def get(self,request,order_id):
        # 1. 获取订单id
        # 2. 根据订单id查询订单信息
        order = OrderInfo.objects.get(order_id=order_id,
                                      status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'],
                                      user=request.user)

        # 3. 生成支付宝支付链接[看支付宝文档]
        """
        1. 准备   ----- 按照 sdk  设置公钥和私钥
        2. 实例化  ------ 创建支付宝实例对象
             appid,             沙箱的应用id
            app_notify_url,     支付宝支付成功之后,通知的url 可以为空
            app_private_key_string=None,
            alipay_public_key_string=None,

        3. 调用方法
        """
        private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(appid=settings.ALIPAY_APPID,
                        app_notify_url=None,
                        app_private_key_string=private_key_string,
                        alipay_public_key_string=public_key_string)

        # 生成支付的 string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject='美多商城支付',
            return_url='http://www.meiduo.site:8080/pay_success.html',
            notify_url="http://www.meiduo.site:8080/pay_success.html"
        )

        # 支付的url
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        return JsonResponse({'code': 0, 'alipay_url': alipay_url})


class PaymentView(LoginRequiredJSONMixin,View):

    def put(self,request):
        # 1,接收参数
        data = request.GET.dict()
        #2,提取参数
        signature = data.pop('sign')

        # 验证数据
        private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(appid=settings.ALIPAY_APPID,
                        app_notify_url=None,
                        app_private_key_string=private_key_string,
                        alipay_public_key_string=public_key_string)
        success = alipay.verify(data, signature)
        if success:
            from apps.payment.models import Payment
            # 4. 保存支付宝订单id和 美多订单id
            # 美多订单id
            order_id = data.get('out_trade_no')
            # 支付宝订单id
            trade_id = data.get('trade_no')
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )
            # 5. 修改订单状态
            OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
            # 6. 返回响应
            return JsonResponse({'code': 0,'errmsg':'ok','trade_id': trade_id})

        return JsonResponse({'code': 400, 'errmsg': '稍后查询支付信息'})